image.png<template>
  <div class="purchase-management">
    <h2>采购管理</h2>
    <!-- 筛选区 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="采购单号">
        <el-input v-model="filters.PurchaseId" placeholder="请输入采购单号" clearable/>
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input v-model="filters.ProductId" placeholder="请输入产品编号" clearable/>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="filters.ProductName" placeholder="请输入产品名称" clearable/>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="filters.State" placeholder="请选择" style="width: 120px;" clearable >
          <el-option label="已入库" value="1" />
          <el-option label="已取消" value="2" />
          <el-option label="采购中" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
     <!-- 新增采购单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="Plus" @click="Tiaozhuan">新增采购单</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
      
      <el-table-column prop="purchaseId" label="订单号" min-width="130"/>
      <el-table-column prop="productName" label="产品名称" min-width="130"/>
      <el-table-column prop="productId" label="产品编号" />
      <el-table-column prop="productSpecs" label="产品规格" min-width="130"/>
      <el-table-column prop="unitId" label="单位" />
      <el-table-column prop="price" label="单价" />
      <el-table-column prop="num" label="数量" />
      <el-table-column prop="total" label="总额" />
      <el-table-column prop="vendorId" label="供应商编号" />
      <el-table-column prop="vendorName" label="供应商名称" />
      <el-table-column prop="state" label="状态"  :formatter="(row:any) => formatStates(row.state)"/>
      <el-table-column prop="recorded" label="是否入账" >
        <template v-slot="scope">
          {{ scope.row.recorded?'是':'否' }}
        </template>
      </el-table-column>
      <el-table-column prop="refund" label="退货" />
      <el-table-column prop="madeTime" label="创建时间" :formatter="formatDate" min-width="180"/>
      <el-table-column label="操作" min-width="250">
        <template #default="scope">
              <el-button type="text" @click="handleView(scope.row)">查看</el-button>
              <el-button type="text" @click="handleEdit(scope.row)" >编辑</el-button>
              <el-button type="text" v-if="scope.row.state!=1" @click="PurView(scope.row)">入库</el-button>
              <el-button type="text" v-if="!scope.row.recorded" @click="handleRecord(scope.row)">入账</el-button>
              <el-button type="text" v-if="scope.row.refund!='退'" @click="handleRefund(scope.row)">退货</el-button>
              <el-button type="text" style="color: #ff4d4f;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页控件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pages.PageIndex"
        v-model:page-size="pages.PageSize"
        :total="pages.totalCount"
        :page-sizes="[10, 15, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" title="采购入库" width="1200px" :close-on-click-modal="false">
       <div class="dialog-content">
      <div class="order-header">
        <div class="order-info">
          <div class="info-item"><span class="label">订单号：</span>{{ productInfo?.purchaseId }}</div>
          <div class="info-item"><span class="label">单据类型：</span>{{ formatOrderType(productInfo?.orderType) }}</div>
          <div class="info-item"><span class="label">状态：</span>{{ formatState(productInfo?.state) }}</div>
        </div>
        
        <div class="order-info">
          <div class="info-item"><span class="label">制单人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">制单日期：</span>{{ formatDate(productInfo?.madeTime) }}</div>
          <div class="info-item"><span class="label">是否入账：</span>{{ productInfo?.recorded ? '是' : '否' }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">供应商编号：</span>{{ productInfo?.vendorId }}</div>
          <div class="info-item"><span class="label">供应商名称：</span>{{ productInfo?.vendorName }}</div>
          <div class="info-item"><span class="label">退货状态：</span>{{ productInfo?.refund }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">联系人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">电话：</span>{{ productInfo?.phone }}</div>
          <div class="info-item"><span class="label">备注：</span>{{ productInfo?.description }}</div>
        </div>
      </div>

        <el-table :data="productInfo?.productDetails || []" border style="margin-top: 20px;">
          <el-table-column prop="productCode" label="产品编码" width="120"/>
          <el-table-column prop="productName" label="产品名称" width="250"/>
          <el-table-column prop="productSpecs" label="规格" width="120"/>
          <el-table-column prop="unitName" label="单位" width="80"/>
          <el-table-column prop="num" label="数量" width="80"/>
          <el-table-column prop="depotName" label="仓库" width="100"/>
          <el-table-column prop="locationName" label="库位" width="120"/>
          <el-table-column prop="price" label="单价" width="100"/>
          <el-table-column prop="total" label="总额" width="100"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    

    <el-dialog v-model="dialogVisibles" title="入库" width="1200px" :close-on-click-modal="false">
       <div class="dialog-content">
      <div class="order-header">
        <div class="order-info">
          <div class="info-item"><span class="label">订单号：</span>{{ productInfo?.purchaseId }}</div>
          <div class="info-item"><span class="label">单据类型：</span>{{ formatOrderType(productInfo?.orderType) }}</div>
          <div class="info-item"><span class="label">状态：</span>{{ formatState(productInfo?.state) }}</div>
        </div>
        
        <div class="order-info">
          <div class="info-item"><span class="label">制单人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">制单日期：</span>{{ formatDate(productInfo?.madeTime) }}</div>
          <div class="info-item"><span class="label">是否入账：</span>{{ productInfo?.recorded ? '是' : '否' }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">供应商编号：</span>{{ productInfo?.vendorId }}</div>
          <div class="info-item"><span class="label">供应商名称：</span>{{ productInfo?.vendorName }}</div>
          <div class="info-item"><span class="label">退货状态：</span>{{ productInfo?.refund }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">联系人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">电话：</span>{{ productInfo?.phone }}</div>
          <div class="info-item"><span class="label">备注：</span>{{ productInfo?.description }}</div>
        </div>
      </div>

        <el-table :data="productInfo?.productDetails || []" border style="margin-top: 20px;">
          <el-table-column prop="productCode" label="产品编码" width="120"/>
          <el-table-column prop="productName" label="产品名称" width="250"/>
          <el-table-column prop="productSpecs" label="规格" width="120"/>
          <el-table-column prop="unitName" label="单位" width="80"/>
          <el-table-column label="批次" width="120">
              <template #default="scope">
                  <el-select v-model="scope.row.batch" placeholder="请选择批次" style="width: 100%" clearable>
                      <el-option v-for="batch in batches" :key="batch.id" :label="batch.bacth" :value="batch.id"/>
                  </el-select>
              </template>
          </el-table-column>
          <el-table-column label="库位" width="150">
              <template #default="scope">
                  <el-select v-model="scope.row.locationId" placeholder="请选择库位" style="width: 100%" clearable>
                      <el-option v-for="location in locations" :key="location.locationId" :label="location.locationName" :value="location.locationId"/>
                  </el-select>
              </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="100"/>
          <el-table-column prop="total" label="总额" width="100"/>
          <el-table-column fixed="right" label="操作" min-width="120">
              <template #default="scope">
                  <el-button link type="primary" size="small" @click="handleAddWareHouse(scope.row)">
                  入库
                  </el-button>
                 
              </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibles = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

     <el-dialog v-model="dialogVisiblesaaaa" title="采购退货" width="1200px" :close-on-click-modal="false">
      <div class="dialog-content">
      <div class="order-header">
        <div class="order-info">
          <div class="info-item"><span class="label">订单号：</span>{{ productInfo?.purchaseId }}</div>
          <div class="info-item"><span class="label">单据类型：</span>{{ formatOrderType(productInfo?.orderType) }}</div>
          <div class="info-item"><span class="label">状态：</span>{{ formatState(productInfo?.state) }}</div>
        </div>
        
        <div class="order-info">
          <div class="info-item"><span class="label">制单人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">制单日期：</span>{{ formatDate(productInfo?.madeTime) }}</div>
          <div class="info-item"><span class="label">是否入账：</span>{{ productInfo?.recorded ? '是' : '否' }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">供应商编号：</span>{{ productInfo?.vendorId }}</div>
          <div class="info-item"><span class="label">供应商名称：</span>{{ productInfo?.vendorName }}</div>
          <div class="info-item"><span class="label">退货状态：</span>{{ productInfo?.refund }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">联系人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">电话：</span>{{ productInfo?.phone }}</div>
          <div class="info-item"><span class="label">备注：</span>{{ productInfo?.description }}</div>
          
        </div>


         <div class="order-info">
                <div class="info-item"><span class="label">退货单号：</span>
                  <el-input-number v-model="refundForm.refundNum"  placeholder="请输入退货单号"></el-input-number>
                </div>
                <div class="info-item"><span class="label">退货原因：</span>
                  <el-input v-model="refundForm.desc" type="textarea" placeholder="请输入退货原因"></el-input>
                </div>
         </div>
      </div>

        <el-table :data="productInfo?.productDetails || []" border style="margin-top: 20px;">
          <el-table-column prop="productCode" label="产品编码" width="120"/>
          <el-table-column prop="productName" label="产品名称" width="250"/>
          <el-table-column prop="productSpecs" label="规格" width="120"/>
          <el-table-column prop="unitName" label="单位" width="80"/>
          <el-table-column prop="num" label="数量" width="80"/>
          <el-table-column prop="depotName" label="仓库" width="100"/>
          <el-table-column prop="locationName" label="库位" width="120"/>
          <el-table-column prop="price" label="单价" width="100"/>
          <el-table-column prop="total" label="总额" width="100"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button type="primary" @click="submitRefund">保存</el-button>
          <el-button @click="dialogVisiblesaaaa = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import http from '@/http/axiosHelper';
import { useRouter } from 'vue-router';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';

import ErrorHandler from '@/utils/errorHandler';
const dialogVisiblesaaaa=ref(false)
// 定义产品详情接口
interface ProductDetails {
  productCode: string;
  productName: string;
  productSpecs: string;
  unitName: string;
  num: number;
  depotName: string;
  locationName: string;
  price: number;
  total: number;
 
}

// 定义采购信息接口
interface ProductInfo {
  id:number;
  purchaseId: string;
  orderType: number;
  state: number;
  contactPerson: string;
  madeTime: string;
  recorded: boolean;
  vendorId: string;
  vendorName: string;
  refund: string;
  phone: string;
  description: string;
  productDetails: ProductDetails[];
    batch?: string; // 批次ID
  locationId?: string; // 库位ID
}

onMounted(()=>{
  onSearch();
})

const router=useRouter();
const filters = reactive({
  PurchaseId: '',
  ProductId: '',
  ProductName: '',
  State: '',
 
})
const Tiaozhuan = () => {
  router.push({ path: '/test' })
}
const pages=reactive({
   PageIndex:1,
  PageSize:15,
  totalPage:0,
  totalCount:0
})
watch(pages,()=>{
  onSearch();
})
const tableData = ref([])
import Purchase from '@/http/PurSale';
import Check from '@/http/Check';
const onSearch=()=> {
 http.get("/scmreadconsul/api/Purchases/ShowPurchase",{
  params:{
   PurchaseId:filters.PurchaseId,
   ProductId:filters.ProductId,
   ProductName:filters.ProductName,
   State:filters.State,
   PageIndex:pages.PageIndex,
   PageSize:pages.PageSize
  }
 }).then(res=>{
  console.log(res.data.items);
  
  tableData.value=res.data.items,
  pages.totalCount=res.data.totalCount,
  pages.totalPage=res.data.totalPage
 })
}

// 分页事件处理
const handleSizeChange = (val: number) => {
  pages.PageSize = val;
  pages.PageIndex = 1; // 重置为第一页
}

const handleCurrentChange = (val: number) => {
  pages.PageIndex = val;
}

// 时间格式化函数
const formatDate = (cellValue: any) => {
  if (!cellValue) return '';
  return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
}

// 是否入账格式化函数
const formatRecorded = (cellValue: any) => {
  return cellValue ? '是' : '否';
}

// 格式化状态
const formatState = (cellValue: any) => {
  switch(cellValue){
    case 1: return '已入库';
    case 2: return '已取消';
    case 3: return '采购中';
    default: return '未知状态';
  }
}
const formatStates = (cellValue: number | string) => {
  const value = Number(cellValue);
  switch (value) {
    case 1:
      return '已入库';
    case 2:
      return '已取消';
    case 3:
      return '采购中';
    default:
      return '未知状态';
  }
};
// 格式化订单类型
const formatOrderType = (cellValue: number | string | undefined) => {
  // 1. 处理undefined和非数字情况
  if (cellValue === undefined) return '未设置';
  const value = Number(cellValue);
  if (isNaN(value)) return '无效类型';

  // 2. 检查是否为预期值
  if (![1, 2, 3].includes(value)) {
    console.warn('收到非预期的orderType值:', cellValue);
    return `未知类型(${cellValue})`;
  }

  // 3. 正常类型转换
  switch(value) {
    case 1:
      return '常规采购';
    case 2:
      return '紧急采购';
    case 3:
      return '退货采购';
    default:
      return '未知状态';
  }
}

// 对话框相关变量
const dialogVisible = ref(false);
const productInfo = ref<ProductInfo>({} as ProductInfo);
const dialogVisibles=ref(false);
// 查看详情
const handleView = async (row:any) => {
  try {
    // 先获取采购信息
    const purchaseResponse = await http.get("/scmreadconsul/api/Purchases/GetPurchaseOne", {
      params: {
        ProductId: row.productId
      }
    });
    // 再获取产品详情
    const productResponse = await http.get("/scmreadconsul/api/Purchases/LookProduct", {
      params: {
        ProductId: row.productId
      }
    });

    productInfo.value = {
      id:row.id,
      ...purchaseResponse.data.data,
      // 如果产品详情是对象则转为数组
      productDetails: Array.isArray(productResponse.data.data) ? productResponse.data.data : [productResponse.data.data]
    };
    dialogVisible.value = true;
  } catch (error) {
    ErrorHandler.handleApiError(error, '获取采购信息失败');
  }
};
//入库
const PurView = async (row:any) => {
  console.log(row.id);
  try {
    // 先获取采购信息
    const purchaseResponse = await http.get("/scmreadconsul/api/Purchases/GetPurchaseOne", {
      params: {
        ProductId: row.productId
      }
    });
    // 再获取产品详情
    const productResponse = await http.get("/scmreadconsul/api/Purchases/LookProduct", {
      params: {
        ProductId: row.productId
      }
    });

    productInfo.value = {
     
      ...purchaseResponse.data.data,
       
      // 如果产品详情是对象则转为数组
      productDetails: Array.isArray(productResponse.data.data) ? productResponse.data.data : [productResponse.data.data],
      id: row.id
    };
    dialogVisibles.value = true;
  } catch (error) {
    ErrorHandler.handleApiError(error, '获取采购信息失败');
  }
};

//退货单
const handleRefund = async (row:any) => {
  try {
    // 先获取采购信息
    const purchaseResponse = await http.get("/scmreadconsul/api/Purchases/GetPurchaseOne", {
      params: {
        ProductId: row.productId
      }
    });
    // 再获取产品详情
    const productResponse = await http.get("/scmreadconsul/api/Purchases/LookProduct", {
      params: {
        ProductId: row.productId
      }
    });

    // 先设置productInfo，然后从其中获取数据
    productInfo.value = {
      id: row.id,
      ...purchaseResponse.data.data,
      productDetails: Array.isArray(productResponse.data.data) 
        ? productResponse.data.data 
        : [productResponse.data.data]
    };

    // 从productInfo中获取数据填充refundForm
    refundForm.refundNum = '1'; // 默认退货数量为1
    refundForm.vendorId = row.vendorId;
    refundForm.vendorName = productInfo.value.vendorName || row.vendorName || "未知供应商"; 
    refundForm.purchaseId = productInfo.value.purchaseId || row.purchaseId || row.id; 
    refundForm.state = 3; // 按需初始化
    refundForm.invoiceType = row.orderType || "1"; 
    refundForm.invoiceState = "0"; 
    refundForm.contact = productInfo.value.contactPerson || row.contactPerson || "未知联系人"; 
    refundForm.phone = productInfo.value.phone || row.phone || "未知电话"; 
    refundForm.desc = "退货申请"; // 默认退货原因
    refundForm.productDetails = productInfo.value.productDetails || [];
    
    // 确保产品相关字段也被填充
    if (refundForm.productDetails.length > 0) {
      const firstProduct = refundForm.productDetails[0];
      refundForm.productName = firstProduct.productName || row.productName || "未知产品";
      refundForm.productSpecs = firstProduct.productSpecs || row.productSpecs || "未知规格";
      refundForm.unitId = firstProduct.unitId || row.unitId || 1;
      refundForm.price = firstProduct.price || row.price || 0;
      refundForm.total = firstProduct.total || row.total || 0;
      refundForm.num = firstProduct.num || row.num || 1;
    } else {
      // 如果没有产品详情，从行数据中获取
      refundForm.productName = row.productName || "未知产品";
      refundForm.productSpecs = row.productSpecs || "未知规格";
      refundForm.unitId = row.unitId || 1;
      refundForm.price = row.price || 0;
      refundForm.total = row.total || 0;
      refundForm.num = row.num || 1;
    }

    // 调试信息：打印填充后的表单数据
    console.log('填充后的退货表单数据:', refundForm);
  
    dialogVisiblesaaaa.value = true;
  } catch (error) {
    ErrorHandler.handleApiError(error, '获取采购信息失败');
  }
};

// 新增：定义批次和库位数据
const batches = ref([{
  id:0,
  bacth:''
}]);
const locations = ref([{
  locationId:0,
  locationName:''
}]);

// 新增：获取批次数据
const getBatches = async () => {
  try {
    const res = await http.get('/scmreadconsul/api/Purchases/GetBatch');
    batches.value = res.data.datas || [];
  } catch (error) {
    ErrorHandler.handleApiError(error, '获取批次数据失败');
  }
};

// 新增：获取库位数据
const getLocations = async () => {
  try {
    const res = await http.get('/scmreadconsul/api/Purchases/GetLocation');
    locations.value = res.data.datas || [];
  } catch (error) {
    ErrorHandler.handleApiError(error, '获取库位数据失败');
  }
};
onMounted(()=>{
  getBatches();
  getLocations();
});

// 编辑采购单
const handleEdit = (row: any) => {
  router.push({ 
    path: '/updpurchase', 
    query: { id: row.id } 
  });
};

// 入账操作
const handleRecord = async (row: any) => {
  try {
    // 调用入账接口
    const response = await http.put('/scmwriteconsul/api/Purchase/UpdateRecord', {
      id: row.id,
      recorded: true
    });

    if (ErrorHandler.handleBusinessError(response, '入账成功')) {
      onSearch(); // 刷新采购列表
    }
  } catch (error) {
    ErrorHandler.handleApiError(error, '入账操作失败');
  }
};

// 删除操作
const handleDelete = async (row: any) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除采购单 "${row.purchaseId}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    const response = await http.put('/scmwriteconsul/api/Purchase/DelPurchase', {
      id: row.id
    });

    if (ErrorHandler.handleBusinessError(response, '删除成功')) {
      onSearch(); // 刷新采购列表
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return;
    }
    ErrorHandler.handleApiError(error, '删除操作失败');
  }
};

// 新增：入库操作方法
const handleAddWareHouse = async (row: any) => {
  // 在这里打印 row 和 row.id
  console.log('row:', row);
  console.log('row.id:', row.id);
  
  // 验证批次和库位是否已选择
if (row.batch == null || row.locationId == null || row.batch === '' || row.locationId === '') {
    ErrorHandler.showWarning('请选择批次和库位');
    return;
}

  try {
    // 调用入库接口
    const response = await http.put('/scmwriteconsul/api/Purchase/AddWareHouse', {
       id: row.id, // 从产品信息获取订单ID
      bacth: String(row.batch), // 批次ID
      locationId: row.locationId, // 库位ID
      state:row.state //状态
    });

    if (ErrorHandler.handleBusinessError(response)) {
      dialogVisibles.value = false; // 关闭对话框
      onSearch(); // 刷新采购列表
    }
  } catch (error) {
    ErrorHandler.handleApiError(error, '入库操作失败');
  }
};

// 定义产品详情接口
interface ProductDetail {
  productId?: number;
  productName: string;
  productCode: string;
  productSpecs: string;
  unitId?: number;
  unitName: string;
  price: number;
  num: number;
  total: number;
  depotName?: string;
  locationName?: string;
}

// 定义退款表单接口
interface RefundForm {
  desc: string;
  phone: string;
  contact: string;
  refundNum: string;
  purchaseId: string;
  vendorName: string;
  invoiceType: string;
  productName: string;
  invoiceState: string;
  productSpecs: string;
  state: number;
  vendorId: number;
  productDetails: ProductDetail[];
  unitId: number;
  price: number;
  total: number;
  num: number;
}
// 类型化响应式表单
const refundForm = reactive<RefundForm>({
  refundNum: '1', // 改为字符串类型
  vendorId: 0,
  vendorName: '',
  purchaseId: '',
  state: 0,
  invoiceType: '',
  invoiceState: '',
  contact: '',
  phone: '',
  desc: '',
  productDetails: [],
  productName: '',
  productSpecs: '',
  unitId: 0,
  price: 0,
  total: 0,
  num: 0
});
// 验证表单数据是否完整
const validateRefundForm = (form: RefundForm): boolean => {
  const requiredFields = [
    'refundNum', 'vendorName', 'purchaseId', 'invoiceType', 
    'invoiceState', 'contact', 'phone', 'desc', 'productName', 
    'productSpecs'
  ];
  
  for (const field of requiredFields) {
    if (!form[field as keyof RefundForm] || form[field as keyof RefundForm] === '') {
      console.error(`缺少必需字段: ${field}`);
      ErrorHandler.showError(`缺少必需字段: ${field}`);
      return false;
    }
  }
  
  return true;
};

// 提交退货信息到后端
const submitRefund = async () => {
  try {
    // 验证表单数据
    if (!validateRefundForm(refundForm)) {
      return;
    }
    
    // 根据API文档，请求需要包装在request字段中
    const requestData = buildRequestData(refundForm);
    
    // 调试信息：打印请求数据
    console.log('最终提交的 requestData:', requestData); // 调试用
    
    const response = await http.post("/scmwriteconsul/api/PurchaseRefunds/AddPurchaseRefund", requestData);
    
    if (ErrorHandler.handleBusinessError(response, "退款申请提交成功")) {
      dialogVisiblesaaaa.value = false; // 关闭对话框
      onSearch(); // 刷新列表数据
      
      // 重置表单
      Object.assign(refundForm, {
        refundNum: '1',
        vendorId: 0,
        vendorName: "",
        purchaseId: "",
        state: 0,
        invoiceType: "",
        invoiceState: "0",
        contact: "",
        phone: "",
        desc: "",
        productDetails: [],
        productName: "",
        productSpecs: "",
        unitId: 0,
        price: 0,
        total: 0,
        num: 0
      });
    }
  } catch (error) {
    ErrorHandler.handleApiError(error, "退款申请提交失败");
  } 
};

const buildRequestData = (form: RefundForm) => ({
  Desc: form.desc,
  Phone: form.phone,
  Contact: form.contact,
  RefundNum: String(form.refundNum || ""),
  PurchaseId: form.purchaseId,
  VendorName: form.vendorName,
  InvoiceType: form.invoiceType,
  ProductName: form.productName,
  InvoiceState: form.invoiceState,
  ProductSpecs: form.productSpecs,
  State: form.state,
  VendorId: form.vendorId,
  ProductDetails: form.productDetails,
  UnitId: form.unitId,
  Price: form.price,
  Total: form.total,
  Num: form.num,
  // 其他字段...
});


</script>

<style scoped>
.purchase-management {
  padding: 24px;
}
.filter-form {
  margin-bottom: 20px;
}


.dialog-content {
  padding: 10px;
}

.order-header {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.order-info {
  display: flex;
  margin-bottom: 10px;
}

.info-item {
  flex: 1;
  margin-right: 15px;
  line-height: 2;
}

.label {
  font-weight: bold;
  color: #606266;
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px 20px;
}
</style>